﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;

namespace DataFlock.CRM.Engine.Common
{
    public abstract class BaseBusinessEntity<T>
    {
        private object _value;
        private Guid _entityId;
        private string _logicalName;

        public Guid EntityId
        {
            get
            {
                return _entityId;
            }
            set
            {
                _entityId = value;
            }
        }

        public string LogicalName
        {
            get
            {
                return _logicalName;
            }
            set
            {
                _logicalName = value;
            }
        }

        public T Value
        {
            get
            {
                if (_value == null)
                {
                    _value = Activator.CreateInstance<T>();
                }

                return (T) (object) _value;
            }
            set
            {
                _value = value;
            }
        }

        public virtual void Save()
        {
            using (var context = CRMHelper.GetContext())
            {
                context.AddObject(this.Value as Entity);

                if (EntityId == Guid.Empty)
                {
                    context.SaveChanges();
                }
                else
                {
                    context.UpdateObject(this.Value as Entity);
                }
            }
        }
    }
}
